package 高频题;

public class 环形链表II_142 {
    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return head == null ? head : head.next;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (true) {
            if (fast == null || fast.next == null) {
                return fast == null ? fast : fast.next;
            }
            slow = slow.next;
            fast = fast.next.next;
            //注意，要让slow和fast先走一次再判断，不然最开始都指向head
            if (fast == slow) {
                break;
            }
        }


        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
